package com.megvii.corelib.filechooser;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.megvii.corelib.R;
import com.megvii.corelib.base.MegviiActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by linyue on 16/3/14.
 */
public class FileChooserActivity extends Activity
{
    protected ListView listView;

    protected View returnButton;

    private ArrayAdapter<String> adapter;

    private Thread thread;

    private boolean setFocused = false;     //是否设置过焦点

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        final FileChooserLayoutParam param = (FileChooserLayoutParam) intent
                .getSerializableExtra(MegviiActivity.KEY_ACTIVITY_PARAM);
        setContentView(param.layoutId);
        adapter = new ArrayAdapter<>(this, param.itemLayoutId, param.itemTextResId);
        listView = (ListView) findViewById(R.id.file_chooser_list);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                ArrayAdapter<String> adapter = (ArrayAdapter<String>) parent.getAdapter();
                String fileAbsolutePath = adapter.getItem(position);
                EventBus.getDefault().post(new FileChooseEvent(fileAbsolutePath));
                finish();
            }
        });
        listView.setAdapter(adapter);
        returnButton = findViewById(R.id.file_chooser_return);
        returnButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //neo取消单击返回按钮清空上次选择结果的操作
//                EventBus.getDefault().post(new FileChooseEvent(null));
                finish();
            }
        });
        thread = new FindFileThread(param.roots, param.postfixes, new FindNewFileListener()
        {
            @Override
            public void onFindNewFile(String fullname)
            {
                adapter.add(fullname);
                if(!setFocused){
                    listView.requestFocus();
                    setFocused = true;
                }
            }

            @Override
            public void onFindCompleted(List<String> allFile)
            {

            }
        });
        thread.start();
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (thread != null)
        {
            thread.interrupt();
        }
    }

    @Override
    public void onBackPressed()
    {
        //neo 取消在退出后
        //EventBus.getDefault().post(new FileChooseEvent(null));
        super.onBackPressed();
    }

    public interface FindNewFileListener
    {
        public void onFindNewFile(String fullname);

        public void onFindCompleted(List<String> allFile);
    }

    public class FindFileThread extends Thread
    {
        private List<String> roots = null;

        private List<String> postfixes = null;

        private Handler hander;

        private volatile boolean terminated = false;

        private FindNewFileListener listener;

        public FindFileThread(List<String> roots, List<String> postfixes,
                FindNewFileListener listener)
        {
            this.roots = roots;
            this.postfixes = postfixes;
            this.hander = new Handler(Looper.getMainLooper());
            this.listener = listener;
        }

        @Override
        public void run()
        {
            final List<String> files = new ArrayList<>();
            for (String root : roots)
            {
                findFilesWithPostfix(root, postfixes, files);
            }
            hander.post(new Runnable()
            {
                @Override
                public void run()
                {
                    synchronized (this)
                    {
                        if (listener != null)
                        {
                            listener.onFindCompleted(files);
                        }
                    }
                }
            });
        }

        @Override
        public void interrupt()
        {
            super.interrupt();
            terminated = true;
            synchronized (this)
            {
                this.listener = null;
            }
        }

        public void findFilesWithPostfix(String rootPath, Collection<String> postfixes,
                List<String> results)
        {
            File file = new File(rootPath);
            if (file.exists())
            {
                if (file.isDirectory())
                {
                    File[] childFiles = file.listFiles();
                    if (childFiles != null)
                    {
                        for (File childFile : childFiles)
                        {
                            if (terminated)
                            {
                                break;
                            }
                            findFilesWithPostfix(childFile.getAbsolutePath(), postfixes, results);
                        }
                    }
                }
                else
                {
                    for (String postfix : postfixes)
                    {
                        //neo取消搜索开头为.的隐藏文件
                        if (file.getName().endsWith(postfix) && file.getName().indexOf(".") != 0)
                        {
                            final String absolutePath = file.getAbsolutePath();
                            results.add(absolutePath);
                            hander.post(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    synchronized (this)
                                    {
                                        if (listener != null)
                                        {
                                            listener.onFindNewFile(absolutePath);
                                        }
                                    }
                                }
                            });
                            break;
                        }
                    }
                }
            }
            else
            {

            }
        }
    }
}
